<?php
/**
 * ################################################
 * #【Description】 商品接口，用户小程序商品数据调用
 * #【Author】 akon
 * #【Date】 2017年6月5日
 * ################################################
 */
namespace Shx\Controller;
use Think\Controller;

class GoodController extends Controller {


    /**
     * 首页商品数据
     */
    public function getGoods(){
        $sql = "SELECT goods_id,goods_name name,shop_price price,original_img small_pic FROM shx_goods limit 10";

        $goodsInfo = M()->query($sql);
        ##数据重组##
        foreach($goodsInfo as $k=>$v){
            $goodsInfo[$k]['small_pic'] = 'http://manager.shenhexin.com/'.$v['small_pic'];
        }
        ##数据重组##
        echo json_encode($goodsInfo);
    }

    /**
     * 首页热门分类
     */
    public function getHotCategory(){
        $hotCategory = M('goods_category')->where(array('is_hot'=>1))->field('id,mobile_name,image')->select();
        foreach($hotCategory as $key=>$val){
            $temp[$key]['id'] = $val['id'];
            $temp[$key]['mobile_name'] = $val['mobile_name'];
            $temp[$key]['img'] = 'http://manager.shenhexin.com' . $val['image'];
        }
        if($hotCategory){
            $res = array(
                'status'     => 1,
                'categories' => $temp
            );
        }else{
            $res = array(
                'status' => 0,
                'msg'    => '网络错误，请稍后重试'
            );
        }
        exit(json_encode($res));
    }

    /**
     * 热门分类商品
     */
    public function getSignalCateProduct(){
        $id = I('get.id');
        $categories = M('goods')->where(array('cat_id' => $id))->field('goods_id,goods_name,original_img')->select();
        $data = M('goods_category')->where(array('parent_id'=>$id))->field('id')->select();
        $cate_ids = implode(',',explodeArr($data,'id'));
        $sql = "SELECT goods_id,goods_name,original_img FROM shx_goods WHERE cat_id IN (".$cate_ids.")";
        $goods_data = M()->query($sql);
        if($goods_data){
            $res = array(
                'status' => 1,
                'goods'  => $goods_data
            );
        }else{
            $res = array(
                'status' => 0
            );
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }


    /**
     * 商品详情接口
     */
    public function getGoodsDetail(){
        $goods_id = I('goods_id');
        $sql = "SELECT a.goods_id,a.goods_name,a.shop_price,a.goods_content,a.store_count,b.image_url FROM shx_goods a JOIN shx_goods_images b ON a.goods_id = b.goods_id WHERE a.goods_id =" . $goods_id;

        $goodsInfo = M()->query($sql);

        foreach($goodsInfo as $key=>$val){
            $val['source'] = "http://manager.shenhexin.com" . $val['image_url'];
            $goods[$val['goods_id']]['goods_id'] = $val['goods_id'];
            $goods[$val['goods_id']]['name'] = $val['goods_name'];
            $goods[$val['goods_id']]['price'] = $val['shop_price'];
            $goods[$val['goods_id']]['store'] = $val['goods_count'];
            $goods[$val['goods_id']]['source'][] = $val['source'];
            //正则提取详情图片src
            $pattern = '/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(?<imgsrc>.*?)\\1[^>]*?\/?\s*>/i';
            preg_match_all($pattern,htmlspecialchars_decode(($val['goods_content'])),$src);
            foreach($src['imgsrc'] as $k=>$v){
                if(strpos($v, 'http://')){
                    $goods[$val['goods_id']]['intro'][$k] = $v;
                }else{
                    $goods[$val['goods_id']]['intro'][$k] = 'http://manager.shenhexin.com'.$v;
                }
            }

//            $goods[$val['goods_id']]['intro'] = $src['imgsrc'];
        }
        $goods = array_values($goods)[0];

        echo json_encode($goods, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
    }

    /**
     * 获取单个商品的数据
     */
    public function getSingalGood1(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $goods = M('goods')->where(array('goods_id'=>$receive['product_id']))->field('goods_id,goods_name,shop_price,original_img')->find();
        if($goods){
            $res = array(
                'status' => 1,
                'goods'  => array(
                    'goods_id' => $goods['goods_id'],
                    'goods_name' => $goods['goods_name'],
                    'shop_price' => printf('%.2f',$goods['shop_price']),
                    'original_img' => 'http://mananger.shenhexin.com' . $goods['original_img']
                )
            );
        }else{
            $res = array(
                'status' => 0,
                'msg'    => '网络错误，请稍后重试'
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    public function getSingalGood(){
        $receive = json_decode(file_get_contents('php://input'),true);
        $goods = M('goods')->where(array('goods_id'=>$receive['product_id']))->field('goods_id,goods_name,shop_price,original_img')->find();
        $address = M('user_address')->where(array('user_id'=>$receive['user_id'],'is_default'=>1))->field('address_id,consignee,address,mobile')->find();
        if($goods) {
            $res = array(
                'status' => 1,
                'goods'  => array(
                    'goods_id' => $goods[ 'goods_id' ],
                    'goods_name' => $goods[ 'goods_name' ],
                    'shop_price' => $goods[ 'shop_price' ],
                    'original_img' => 'http://manager.shenhexin.com' . $goods[ 'original_img' ]
                ),
                'address' => $address
            );
        }else{
            $res = array(
                'status' => 0,
                'msg' => '网络错误，请稍后重试'
            );
        }
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取分类数据
     */
    public function getCategory(){
        /*$cate_sql = "SELECT id,mobile_name
                     FROM shx_goods_category
                     WHERE
                     LENGTH(parent_id_path) - LENGTH(REPLACE(parent_id_path, '_', '')) = 2
                     LIMIT 0,14";*/
        $cate_sql = "SELECT id,name
                     FROM shx_goods_category
                     WHERE
                     level = 1
                     LIMIT 0,14";
        $categories = M()->query($cate_sql);

        $res = array(
            'categories' => $categories
        );
        exit(json_encode($res, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
    }

    /**
     * 获取热门商品数据
     */
    public function getHotProduct(){
        $products = M('goods')->field('goods_id,goods_name,original_img')->order('sales_sum desc')->limit(20)->select();
        if($products){
            $res = array(
                'status' => 1,
                'products' => $products
            );
        }else{
            $res = array(
                'status' => 0,
                'msg' => '网络错误，请稍后重试'
            );
        }
	
        exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 获取分类商品数据
     * 【METHOD】 GET
     */
    public function getCategoryProduct(){
        $id = I('get.id');
        if(!$id){
            $res = array(
                'status' => 0,
                'msg'    => '系统错误，请重新操作'
            );
        }else{
            $cates_result  = M('goods_category')->where(array('parent_id'=>$id))
                                               ->field('id,name')
                                               ->select();
            $cates_id_arr = explodeArr($cates_result, 'id');
            $cates_id_str = implode(',' ,$cates_id_arr);
            $sql = "SELECT goods_id,cat_id,goods_name,original_img
                    FROM shx_goods
                    WHERE cat_id
                    IN("."$cates_id_str".")";
            $products = M()->query($sql);

            foreach($cates_result as $c_key=>$cate){
                $result[$cate['id']] = array(
                    'id'   => $cate['id'],
                    'name' => $cate['name']
                );
                foreach($products as $p_key=>$prod){
                    if($prod['cat_id'] == $cate['id']){
                        $result[$cate['id']]['products'][$p_key] = array(
                            'goods_id' => $prod['goods_id'],
                            'goods_name'   => $prod['goods_name'],
                            'original_img' => $prod['original_img'],
                            'cat_id' => $prod['cat_id']
                        );
                    }
                }
            }
            if($result){
                $res = array(
                    'status' => 1,
                    'goods' => $result
                );
            }else{
                $res = array(
                    'status' => 0,
                    'msg'    => '系统错误，请稍后重试'
                );
            }
            exit(json_encode($res, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        }
    }


    /**
     * 活动区域商品获取
     */
    public function getProductForActivity(){
        $data = M('goods')->where(array('give_integral'=>2))->field('goods_id,activity_img')->select();

        if($data){
            $res = array(
                'status' => 1,
                'products' => $data
            );
        }else{
            $res = array(
                'status' => 0,
                'msg'    => '暂无商品'
            );
        }
        exit(json_encode($res,JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }

    /**
     * 保存登录用户信息
     */
    public function saveUserInfo(){
        $userInfo = I('userInfo');
        $openId = I('openId');
        echo $openId;
        $userInfo = json_decode(htmlspecialchars_decode($userInfo),true);  //将用户信息转换为数组
        //查询数据表中是否有此用户
        $res = M('user')->where(array('open_id'=>$openId))->count();
        if(!$res){
            $info = array(
                'open_id' => $openId,
                'nickname' => $userInfo['nickName'],
                'avatarUrl' => $userInfo['avatarUrl']
            );
            $id = M('user')->add($info);
            if($id){
                echo $id;
            }
        }else{
            echo "用户已存在";
        }

    }


    /**
     * 解密openId
     * 1、获取code
     * 2、code换取session_key
     * 3、
     */
    public function getOpenId(){
        $code = I('code');
        $session_key_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.C('APPID').'&secret='.C('APPSECRET').'&js_code='.$code.'&grant_type=authorization_code';
        $openId          = _curl($session_key_url);
        //生成session，用于用户身份唯一性识别
        $session_key   = takeUniqueStr();
        $session_value = takeUniqueStr();
        session(array($session_key, session_value), time() + 7200);
        $res = array(
            'openId' => json_decode($openId, true)['openid'],
            'session_key' => $session_value
        );
        exit(json_encode($res));
    }

}
